package com.youmingxing.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tencent.download.Downloader;
import com.tencent.download.core.DownloadResult;
import com.umeng.analytics.MobclickAgent;
import com.youmingxing.R;
import com.youmingxing.activity.selfInfo.MyAuditionGoingActivity;
import com.youmingxing.activity.selfInfo.PersonalInfoActivity;
import com.youmingxing.adpter.CommentsAdapter;
import com.youmingxing.bean.Comment;
import com.youmingxing.bean.Content;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.dialog.ShareDialog;
import com.youmingxing.network.AccountApi;
import com.youmingxing.network.AllStarApi;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.utils.Const;
import com.youmingxing.utils.DisplayUtil;
import com.youmingxing.utils.LogUtil;
import com.youmingxing.utils.TimeUtils;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.RefreshListView;
import com.youmingxing.view.TextLengthWatcher;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import me.iwf.photopicker.PhotoPagerActivity;


/**
 * @author chihiro(xuchang)
 * @since 2015-9-3
 *  * 作品详情
 */

public class ContentDetailActivity extends BaseActivity implements View.OnClickListener, CommentsAdapter.ThumbUpListener, TextView.OnEditorActionListener, RefreshListView.OnLoadMoreListener {

    Content content;
    View header;
    int contentId;
    RefreshListView mListComment;
    RefreshListView mListCommentHot;
    List<Comment> mHotList = new ArrayList<>();
    List<Comment> mLatestList = new ArrayList<>();
    CommentsAdapter hotCommentsAdapter;
    CommentsAdapter latestCommentsAdapter;
    //评论框
    EditText commentEt;
    //作品详情
    ImageView userImage;
    ImageView identityImage;
    ImageView contentImage;
    TextView nickName;
    TextView contentTitle;
    TextView shareTv;
    TextView likeTv;
    TextView commentTv;
    TextView btnFocus;
    ImageView playBtn;
    View hotCommentMoreBtn;

    Downloader downloader;
    ArrayList<String> photoPaths = new ArrayList<>();
    Handler handler = new Handler();
    boolean isSending = false;
    // 获取热门评论和最新评论的接口是一起的,onResume中刷新改接口,如果最新评论有内容且改变量为false,则不需要刷新
    boolean needUpdateLatestComments = false;
    int toUid = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_content_detail);
        contentId = getIntent().getExtras().getInt("content_id");
        showDialog();
        downloader = new Downloader(this, Const.APP_ID, "content");
        setTopbarName(R.string.title_activity_content_detail);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getContentDetail();
        HashMap<String, String> value = new HashMap<>();
        value.put(contentId + "", "1");
        MobclickAgent.onEvent(this, "100", value);
    }

    @Override
    public void onErrorClick() {
        getContentDetail();
    }

    private void getContentDetail() {
        AllStarApi.getContentDetail(contentId, new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                showErrorPage(false);
                content = new Content(response.optJSONObject("data"));
                if (header == null) {
                    header = View.inflate(ContentDetailActivity.this, R.layout
                            .header_content_detail, null);
                    mListComment = (RefreshListView) findViewById(R.id.list_comments);
                    mListComment.addHeaderView(header);
                    initView();
                }
                updateView();
                getCommentsFromServer();
            }

            @Override
            public void onFail(int statusCode, String statusText) {
                super.onFail(statusCode, statusText);
                showErrorPage(true);
            }
        });
    }

    private void getCommentsFromServer() {
        AllStarApi.getLatestComments(content.getId(), -1, -1, new BaseJsonHandler(this) {
            @Override
            public void onSuccessWithData(JSONObject response) {
                mListComment.endLoadMore();
                //热门评论
                LogUtil.i("-------response--","" +response);
                JSONObject hot = response.optJSONObject("data").optJSONObject("hot");
                JSONArray hotdata = hot.optJSONArray("item");
                int count = hot.optInt("count");
                if (hotdata != null && hotdata.length() > 0) {
                    mHotList.clear();
                    int hotCommentNum = hotdata.length() > 5 ? 5 : hotdata.length();
                    if (count > 3) {
                        //显示更多按钮
                        hotCommentMoreBtn.setVisibility(View.VISIBLE);
                    } else {
                        hotCommentMoreBtn.setVisibility(View.INVISIBLE);
                    }
                    for (int i = 0; i < hotCommentNum; i++) {
                        Comment comment = new Comment(hotdata.optJSONObject(i));
                        mHotList.add(comment);
                    }
                    hotCommentsAdapter.setData(mHotList);
                    mListCommentHot.setVisibility(View.VISIBLE);
                } else {
                    mListCommentHot.setVisibility(View.GONE);
                }
                //最新评论
                if (mLatestList.size() == 0 || needUpdateLatestComments) {
                    mLatestList.clear();
                    JSONArray latestData = response.optJSONObject("data").optJSONArray("list");
                    if (latestData.length() == 0) {
                        mListComment.noData("暂时还没有人评论哦");
                    } else if (latestData.length() < 20) {
                        mListComment.noMoreData();
                    }
                    for (int i = 0; i < latestData.length(); i++) {
                        Comment comment = new Comment(latestData.optJSONObject(i));
                        mLatestList.add(comment);
                    }
                    latestCommentsAdapter.setData(mLatestList);
                    if (needUpdateLatestComments) {
                        mListComment.setSelection(1);
                        if (latestData.length() == 20) {
                            mListComment.reset();
                        }
                    }
                    needUpdateLatestComments = false;
                }
                DialogManager.dismissDialog();

            }

            @Override
            public void onFail(int statusCode, String statusText) {
                super.onFail(statusCode, statusText);
                mListComment.endLoadMore();
                mListComment.noMoreData();
            }
        });
    }

    private void initView() {
        //navigation bar
        setLeftAndrightTv(true, true, true, -1, null, null, this);
        rightImage.setImageResource(R.mipmap.share_btn);

        //header
        userImage = (ImageView) findViewById(R.id.content_avatar);
        userImage.setOnClickListener(this);
        contentImage = (ImageView) findViewById(R.id.content_image);
        contentImage.setOnClickListener(this);
        identityImage = (ImageView) findViewById(R.id.authentication_img);
        nickName = (TextView) findViewById(R.id.content_actor_name);
        nickName.setOnClickListener(this);
        playBtn = (ImageView) findViewById(R.id.content_video_play);
        playBtn.setOnClickListener(this);
        contentTitle = (TextView) findViewById(R.id.content_title);
        contentTitle.setText(content.getTitle());
        //点赞评论分享
        shareTv = (TextView) findViewById(R.id.content_share_tv);
        shareTv.setOnClickListener(this);
        likeTv = (TextView) findViewById(R.id.content_like_tv);
        likeTv.setOnClickListener(this);
        commentTv = (TextView) findViewById(R.id.content_comment_tv);
        commentTv.setOnClickListener(this);
        //投加油票
        findViewById(R.id.content_ticket_button).setOnClickListener(this);
        btnFocus = (TextView) findViewById(R.id.btn_focus);
        btnFocus.setOnClickListener(this);
        LayoutInflater inflater = LayoutInflater.from(this);
        //hot
        mListCommentHot = (RefreshListView) findViewById(R.id.list_comments_hot);
        mListCommentHot.setEnableScroll(false);
        mListCommentHot.setFootVisible(false);
        mListCommentHot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id < 0) {
                    return;
                }
                Comment comment = mHotList.get(position - 1);
                toUid = comment.u_id;
                commentEt.setHint("回复" + comment.u_name);
                DisplayUtil.showSoftInput(commentEt);

            }
        });
        hotCommentsAdapter = new CommentsAdapter(this, this);
        View hotHeaderView = inflater.inflate(R.layout.header_comment, null);
        hotCommentMoreBtn = hotHeaderView.findViewById(R.id.layout_more);
        hotCommentMoreBtn.setOnClickListener(this);
        mListCommentHot.addHeaderView(hotHeaderView);
        mListCommentHot.setAdapter(hotCommentsAdapter);
        ((TextView) hotHeaderView.findViewById(R.id.tv_left)).setText("热门评论");


        //not hot
        mListComment.setOnLoadMoreListener(this);
        latestCommentsAdapter = new CommentsAdapter(this, this);
        View latestHeaderView = inflater.inflate(R.layout.header_comment, null);
        ((TextView) latestHeaderView.findViewById(R.id.tv_left)).setText("最新评论");
        latestHeaderView.findViewById(R.id.layout_more).setVisibility(View.INVISIBLE);
        mListComment.addHeaderView(latestHeaderView);
        mListComment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id < 0) return;
                Comment comment = mLatestList.get(position - 2);
                toUid = comment.u_id;
                commentEt.setHint("回复" + comment.u_name);
                DisplayUtil.showSoftInput(commentEt);

            }
        });
        mListComment.setAdapter(latestCommentsAdapter);

        commentEt = (EditText) findViewById(R.id.et_comment);
        commentEt.setOnEditorActionListener(this);
        commentEt.addTextChangedListener(new TextLengthWatcher(100, commentEt));

    }


    @Override
    public void onClick(View v) {
        Intent intent;

        switch (v.getId()) {
            case R.id.layout_more:
                intent = new Intent(ContentDetailActivity.this, CommentListActivity.class);
                intent.putExtra("id", content.getId());
                startActivity(intent);
                break;
            case R.id.content_avatar:
            case R.id.content_actor_name:
                intent = new Intent(this, PersonalInfoActivity.class);
                intent.putExtra("u_id", content.getU_id());
                startActivity(intent);
                break;
            case R.id.content_video_play:
                AccountApi.getVedioSign(new BaseJsonHandler(ContentDetailActivity.this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        String url = content.getUrl() + "?sign=" + response.optJSONObject
                                ("data")
                                .optString("sign");
                        intent.setDataAndType(Uri.parse(url), "video/*");
                        startActivity(intent);
                    }
                });

                break;
            case R.id.content_image:
                String url = content.getUrl();
                if (content.getType() == 2) {
                    break;
                }
                if (downloader.hasCache(url)) {
                    File file = downloader.getCacheFile(url);
                    if (file != null && file.exists()) {
                        photoPaths.clear();
                        photoPaths.add(file.getPath());
                        enterPhotoPager();
                    }
                } else {
                    showDialog();
                    downloader.download(url, new Downloader.DownloadListener() {
                        @Override
                        public void onDownloadCanceled(String s) {

                        }

                        @Override
                        public void onDownloadFailed(String s, DownloadResult downloadResult) {

                        }

                        @Override
                        public void onDownloadSucceed(String s, DownloadResult downloadResult) {
                            photoPaths.clear();
                            photoPaths.add(downloadResult.getPath());
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    hideDialog();
                                }
                            });
                            enterPhotoPager();
                        }

                        @Override
                        public void onDownloadProgress(String s, long l, float v) {

                        }
                    });
                }
                break;
            case R.id.header_iv_right:
            case R.id.content_share_tv:
                //分享
                showShareDialog();
                break;
            case R.id.content_like_tv:
                AllStarApi.thumsUpContent(content.getId(), new BaseJsonHandler(ContentDetailActivity.this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        int result = response.optJSONObject("data").optInt("result");
                        if (result == 1) {
//                            showToast("点赞成功");
                            content.thumbsup_num++;
                            content.my_thumbsup = true;
                            updateView();
                        } else if (result == 2) {
                            showToast("点赞过了");
                        } else {
                            showToast("出错了");
                        }
                    }
                });
                break;
            case R.id.content_comment_tv:
                DisplayUtil.showSoftInput(commentEt);
                break;
            case R.id.btn_focus:
                //自己不能关注自己
                if (content.getU_id() == GlobalDataManager.userId) {
                    showToast("自己不能关注自己哦");
                    return;
                }
                //是我关注的人
                showDialog("正在提交");
                int operate = 0;
                if (!content.my_follow) {
                    operate = 1;
                }
                AllStarApi.focus(content.getU_id(), operate, new BaseJsonHandler(this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        int result = response.optJSONObject("data").optInt("result");
                        if (result == 1) {
                            if (content.my_follow) {
                                showToast("您已成功取消关注");
                                content.my_follow = false;
                                content.follow_num--;
                            } else {
                                showToast("您已成功关注");
                                content.my_follow = true;
                                content.follow_num++;
                            }
                            setBtnFocusStyle();
                            ((TextView) findViewById(R.id.focus_num)).setText(content.follow_num + "");
                        }
                    }
                });
                break;
            case R.id.content_ticket_button:
                DialogManager.showDialog(this, "正在提交");
                AllStarApi.vote(content.getU_apply_id(), 1, new BaseJsonHandler
                        (this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        int result = response.optJSONObject("data").optInt("result");
                        switch (result) {
                            case 1:
                                showToast("加油成功");
                                break;
                            case 0:
                                showToast("系统错误");
                                break;
                            case 2:
                                long time = response.optJSONObject("data").optLong("gen_duetime");
                                AlertDialog.Builder builder = new AlertDialog.Builder
                                        (ContentDetailActivity.this);
                                builder.setCancelable(false).setTitle("您的加油票不足1张").setMessage
                                        (TimeUtils.parseSecondToString(time) + "后,您将得到一张新票")
                                        .setPositiveButton("确定", null).show();
                                break;
                        }
                    }
                });
                break;
            case R.id.content_audition_type:
                intent = new Intent(ContentDetailActivity.this, MyAuditionGoingActivity.class);
                intent.putExtra("id", content.getU_apply_id());
                startActivity(intent);
                break;
        }
    }

    private void enterPhotoPager() {
        Intent intent = new Intent(this, PhotoPagerActivity.class);
        intent.putExtra(PhotoPagerActivity.EXTRA_CURRENT_ITEM, 0);
        intent.putExtra(PhotoPagerActivity.EXTRA_PHOTOS, photoPaths);
        intent.putExtra(PhotoPagerActivity.EXTRA_SHOW_DELETE, false);
        startActivity(intent);
    }

    private void showShareDialog() {
        Intent intent = new Intent(ContentDetailActivity.this, ShareDialog.class);
        intent.putExtra("id", content.getId());
        intent.putExtra("entrance", 3);
        startActivity(intent);
    }

    private void updateView() {
        commentTv.setText(content.getComment_num() + "");
        shareTv.setText(content.getShare_num() + "");
        likeTv.setText(content.getThumbsup_num() + "");
        Glide.with(getApplicationContext()).load(content.getU_headimg()).bitmapTransform(new
                CropCircleTransformation(this))
                .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar).crossFade().into
                (userImage);
        nickName.setText(content.getU_name());
        //浏览量
        TextView browseNumber = (TextView) findViewById(R.id.browse_number);
        browseNumber.setText("浏览量 " + content.browse_num);
        ((TextView) findViewById(R.id.focus_num)).setText(content.follow_num + "");
        //点赞
        if (content.my_thumbsup) {
            Drawable like = getResources().getDrawable(R.mipmap.liked_big);
            likeTv.setCompoundDrawablesWithIntrinsicBounds(like, null, null, null);
        }
        Glide.with(getApplicationContext()).load(content.getThumbnail())
                .placeholder(R.drawable.default_16_9).error(R.drawable.default_16_9).crossFade().into(contentImage);

//        //认证
//        if (content.isU_auth()) {
//            Drawable auth = getResources().getDrawable(R.mipmap.identification);
//            nickName.setCompoundDrawablesWithIntrinsicBounds(null, null, auth, null);
//        } //官方

        LogUtil.i("--------detail---", content.user_type + "  name" + content.getU_name() +"-url--" + AllStarApi.getUserMarkIcon
                (Integer.parseInt(content.user_type)) );
        Glide.with(getApplicationContext()).load(AllStarApi.getUserMarkIcon
                (Integer.parseInt(content.user_type))).
                crossFade().into(identityImage);

//        if (content.user_type.equals("11")) {
//            Drawable auth = getResources().getDrawable(R.mipmap.gf);
//            nickName.setCompoundDrawablesWithIntrinsicBounds(null, null, auth, null);
//        }
//        if (!content.isU_auth() && content.user_type.equals("10")) {
//            nickName.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
//        }

        if (content.getType() == 2) {
            playBtn.setVisibility(View.VISIBLE);

        } else {
            playBtn.setVisibility(View.INVISIBLE);
        }
        View ticketsView = findViewById(R.id.content_comeon_layout);
        TextView auditionType = (TextView) findViewById(R.id.content_audition_type);
        if (content.getU_apply_id() != -1) {
            ticketsView.setVisibility(View.VISIBLE);
            auditionType.setText(content.u_apply_tip);
            auditionType.setOnClickListener(this);
        } else {
            ticketsView.setVisibility(View.GONE);
        }
        setBtnFocusStyle();
    }

    void setBtnFocusStyle() {
        if (content.my_follow) {
            //是我关注的
            btnFocus.setText("已关注");
        } else {
            //不是
            btnFocus.setText("+关注");
        }
    }


    @Override
    public void thumbUpSuccess() {
        getCommentsFromServer();
    }

    @Override
    public void thumbUpFailed(String failReason) {
        showToast(failReason);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
            if (commentEt.getText().toString().isEmpty()) {
                showToast("您还没有输入内容哦");
                return true;
            }
            if (isSending) {
                return true;
            }
            if (commentEt.getText().toString().equals("--cleancache")) {
                downloader.cleanCache();
                showToast("clean cache");
                commentEt.setText("");
                DisplayUtil.hideSoftInput(commentEt);
                return true;
            }
            AllStarApi.comment(commentEt.getText().toString(), this.content.getId(), toUid, new
                    BaseJsonHandler(this) {
                        @Override
                        public void onSuccessWithData(JSONObject response) {
                            isSending = false;
                            if (response.optJSONObject("data").optInt("result") == 1) {
                                //发送成功
                                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                                        .hideSoftInputFromWindow(ContentDetailActivity.this.getCurrentFocus()
                                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                                needUpdateLatestComments = true;
                                getCommentsFromServer();
                                commentEt.setText("");
                                commentEt.setHint(R.string.i_want_comment);
                                toUid = -1;
                                DisplayUtil.hideSoftInput(commentEt);
                            } else {
                                showToast("评论失败");
                            }
                        }

                        @Override
                        public void onFail(int statusCode, String statusText) {
                            super.onFail(statusCode, statusText);
                            isSending = false;

                        }
                    });
            isSending = true;
            return true;
        }
        return false;
    }

    @Override
    public void onLoadMore() {
        if (mLatestList.size() == 0)
            return;
        Comment last = mLatestList.get(mLatestList.size() - 1);
        AllStarApi.getLatestComments(content.getId(), last.createtime, last.id, new
                BaseJsonHandler(this) {
                    @Override
                    public void onSuccessWithData(JSONObject response) {
                        mListComment.endLoadMore();
                        JSONArray latestData = response.optJSONObject("data").optJSONArray("list");
                        if (latestData.length() < 20) {
                            mListComment.noMoreData();
                        }
                        for (int i = 0; i < latestData.length(); i++) {
                            Comment comment = new Comment(latestData.optJSONObject(i));
                            mLatestList.add(comment);
                        }
                        latestCommentsAdapter.setData(mLatestList);
                    }
                });
    }
}
